import React from "react";
import { useNavigate } from "react-router-dom";
import { connect } from "react-redux";

// antd
import { Layout, Menu, Dropdown, Avatar } from "antd";
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined,
} from "@ant-design/icons";

const { Header } = Layout;

const TopHeader = (props: {
  changeCollapsed: Function;
  changeLogout: Function;
  isCollapsed: boolean;
}) => {
  // const [collapsed, setCollapsed] = useState(false);

  const navigate = useNavigate();

  const toggle = () => {
    // setCollapsed(!collapsed);
    props.changeCollapsed();
  };

  const {
    role: { roleName },
    username,
  } = JSON.parse(localStorage.getItem("user") || "");

  const menu = (
    <Menu>
      <Menu.Item key={1}>{roleName}</Menu.Item>
      <Menu.Item key={2}>消息</Menu.Item>
      <Menu.Item
        key={3}
        danger
        onClick={() => {
          localStorage.removeItem("user");
          navigate("/login", { replace: true });
          props.changeLogout();
          // props.history.replace("/login");
        }}
      >
        退 出
      </Menu.Item>
    </Menu>
  );

  return (
    <Header className="site-layout-background" style={{ padding: "0 16px" }}>
      {React.createElement(
        props.isCollapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
        {
          className: "trigger",
          onClick: toggle,
        }
      )}
      <div style={{ float: "right" }}>
        <Dropdown overlay={menu}>
          <div>
            <Avatar size={40} icon={<UserOutlined />} />
            <span style={{ marginLeft: "10px" }}>{username}</span>
          </div>
        </Dropdown>
      </div>
    </Header>
  );
};

const mapStateToProps = ({
  CollApsedReducer: { isCollapsed },
}: {
  CollApsedReducer: { isCollapsed: boolean };
}) => {
  return {
    isCollapsed,
  };
};

const mapDispatchToProps = {
  changeCollapsed() {
    return {
      type: "change_collapsed",
    };
  },
  changeLogout() {
    return {
      type: "change_Login",
      payload: false,
    };
  },
};

export default connect(mapStateToProps, mapDispatchToProps)(TopHeader);
